package com.tbit.uqbike.client.filter.dubbo;

import cn.hutool.core.util.StrUtil;
import com.tbit.common.constant.CommonConstant;
import com.tbit.common.utils.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;


/**
 * rpc调用过滤器
 * @author Zhang Zhi Liang
 * @date 2024/4/25 15:30
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER,CommonConstants.CONSUMER})
public class DubboFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = null;
        try{
            RpcContext rpcContext = RpcContext.getContext();
            String traceId = "";
            // 调用方
            if (rpcContext.isConsumerSide()){
                // traceId 为空
                if (StrUtil.isBlank(TraceUtil.getTraceIdByLocal())){
                    traceId = TraceUtil.buildTraceId();
                }else {
                    traceId = TraceUtil.getTraceIdByLocal();
                }
                // 设置保存本服务调用traceId
                TraceUtil.setTraceId(traceId);
                // 设置保存Rpc调用traceId
                rpcContext.setAttachment(CommonConstant.TRACE_ID,traceId);
            }
            // 提供方
            if (rpcContext.isProviderSide()){
                traceId = rpcContext.getAttachment(CommonConstant.TRACE_ID);
                TraceUtil.setTraceId(traceId);
            }
        }catch (Exception e){
            log.error("dubbo调用中traceId操作异常！",e);
        }finally {
            result = invoker.invoke(invocation);
            // 执行完毕后进行
            TraceUtil.cleanTraceId();
        }
        return result;
    }
}
